<?php
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace pays\Gateways\sxfpay;

class Sxfpay{
    protected $config;
    protected $gateway_qrcode_url = 'https://icm-management.suixingpay.com/management/qr/activeScan';
    protected $gateway_jsapi_url = 'https://icm-management.suixingpay.com/management/qr/jsapiScan';
    protected $privateKey = "private_key.pem";
    protected $sxfpublic="<<<EOD
            -----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjo1+KBcvwDSIo+nMYLeOJ19Ju4ii0xH66ZxFd869EWFWk/EJa3xIA2+4qGf/Ic7m7zi/NHuCnfUtUDmUdP0JfaZiYwn+1Ek7tYAOc1+1GxhzcexSJLyJlR2JLMfEM+rZooW4Ei7q3a8jdTWUNoak/bVPXnLEVLrbIguXABERQ0Ze0X9Fs0y/zkQFg8UjxUN88g2CRfMC6LldHm7UBo+d+WlpOYH7u0OTzoLLiP/04N1cfTgjjtqTBI7qkOGxYs6aBZHG1DJ6WdP+5w+ho91sBTVajsCxAaMoExWQM2ipf/1qGdsWmkZScPflBqg7m0olOD87ymAVP/3Tcbvi34bDfwIDAQAB\n-----END PUBLIC KEY-----
            EOD";
    public function __construct($config)
    {
        $this->config = $config;
    }
    //小程序支付
    public function miniapp($order=array()){
        if(!is_array($order)){
            die("请传入数组参数!");
        }
        if(!$this->check_params($order,["openid"])){
            die("请传入Openid!");
        }
        if(!$this->check_params($order,["appid"])){
            die("请传入Appid!");
        }
        if(!$this->check_params($order,["total"])){
            die("请传入付款金额!");
        }
        if(!$this->check_params($order,["ordersn"])){
            die("请传入订单编号!");
        }
        if(!$this->check_params($order,["appsecret"])){
            die("请传入AppSecret参数!");
        }
        if(!$this->check_params($order,["notify"])){
            die("请传入回调地址参数!");
        }
        $sxf_jsapi_data = array(
            "orgId"=>$this->config["org_id"],
            "reqId"=>time(),
            "signType"=>"RSA",
            "timestamp"=>date("Ymdhis"),
            "version"=>"1.0",
            "reqData"=>array(
                "mno"=>$order["appid"],
                "ordNo"=>$order["ordersn"],//商户订单号
                "amt"=>$order["total"],//订单总金额
                "payType"=>"JSAPI",
                "subject"=>"订单支付:".$order["ordersn"],
                "subOpenid"=>$order["openid"],
                "subAppid"=>$order["appsecret"],
                "notifyUrl"=>$order["notify"]
            )
        );
        $sxf_jsapi_data = $this->argSort($sxf_jsapi_data);
        $mystr = $this->createLinkstring($sxf_jsapi_data);
        if (!file_exists(__DIR__ . '/key/'.$this->privateKey)) {
            die("Sxf privateKey is not exist.");
        }
        $privateKey = __DIR__ . '/key/'.$this->privateKey;
        $sign = $this->rsaSign($mystr,$privateKey);
        $sxf_jsapi_data['sign']=$sign;
        $post_data = json_encode($sxf_jsapi_data);
        $tmpInfo = $this->HttpPost($this->gateway_jsapi_url,$post_data);
        $tmpInfo=json_decode($tmpInfo,true);
        //dump($tmpInfo);
        if($tmpInfo["code"] == "SXF0000" && $tmpInfo['respData']['bizCode'] == 0000 ){
            $result = $tmpInfo;
            $jsApiParameters = array(
                "appId"=>$result["respData"]["payAppId"],//公众号名称，由商户传入
                "timeStamp"=>$result["respData"]["payTimeStamp"],//时间戳，自1970年以来的秒数
                "nonceStr"=>$result["respData"]["paynonceStr"], //随机串     
                "package"=>$result["respData"]["payPackage"],    
                "signType"=>$result["respData"]["paySignType"],//微信签名方式：     
                "paySign"=>$result["respData"]["paySign"]//微信签名 
            );
            //uuid-更新订单
            //Db::name("order_list")->where("sn",$sxf_data['ordersn'])->update(['trid'=>$result['respData']['uuid']]);
            return array("code"=>200,"data"=>$jsApiParameters);
        }else{
            return array("code"=>202,"data"=>$tmpInfo);
        }
    }
    //扫码支付
    public function qrcode($order=array()){
        if(!is_array($order)){
            die("请传入数组参数!");
        }
        if(!$this->check_params($order,["mno"])){
            die("请传入随行付商户号!");
        }
        if(!$this->check_params($order,["total"])){
            die("请传入付款金额!");
        }
        if(!$this->check_params($order,["ordersn"])){
            die("请传入订单编号!");
        }
        if(!$this->check_params($order,["subject"])){
            die("请传入付款描述参数!");
        }
        if(!$this->check_params($order,["notify"])){
            die("请传入回调地址参数!");
        }
        $mygoods['reqData']['payType'] = "WECHAT";
        $mygoods['orgId'] = $this->config["org_id"];
        $mygoods['reqData']['amt'] = $order['total'];
        $mygoods['reqData']['mno'] = $order['mno'];
        $mygoods['reqData']['ordNo'] = $order['ordersn'];
        $mygoods['reqData']['subject'] = $order['subject'];
        $mygoods['reqData']['notifyUrl'] = $order["notify"];
        $mygoods['reqId'] = $order['ordersn'];
        $mygoods['signType'] = "RSA";
        $mygoods['timestamp'] = date("Ymdhis");
        $mygoods['version'] = "1.0";
        $mygoods = $this->argSort($mygoods);
        $mystr = $this->createLinkstring($mygoods);
        if (!file_exists(__DIR__ . '/key/'.$this->privateKey)) {
            die("Sxf privateKey is not exist.");
        }
        $privateKey = __DIR__ . '/key/'.$this->privateKey;
        $sign = $this->rsaSign($mystr,$privateKey);
        $mygoods['sign'] = $sign;
        $datajsonstr = json_encode($mygoods);
        $sign = urlencode($sign);
        $tmpInfo = $this->HttpPost($this->gateway_qrcode_url,$datajsonstr);
        $tmpInfo=json_decode($tmpInfo,true);
        $info=$tmpInfo;
        if(empty($info['sign'])){
            return json_encode($info);
        }else{
            $newsign=$info['sign'];
        }
        unset($info['sign']);
        ksort($info);
        return $info['respData']['payUrl'];
    }
    protected function check_params($data, $c = array())
    {
        if (empty($c)) {
            return $data;
        }
        foreach ($c as $k => $v) {
            if (array_key_exists($v, $data) == false) {
                return false;
            }
        }
        return $data;
    }
    protected function argSort($para){
        ksort($para);
        return $para;
    }
    protected function createLinkstring($para){
        $params = array();
        foreach($para as $key => $value){
            if(is_array($value)){
                    $value=stripslashes(json_encode($value,JSON_UNESCAPED_UNICODE));
            }
            $params[] = $key .'='. $value ;
        }
        $data = implode("&", $params);
        return $data;
    }
    protected function rsaSign($data, $private_key_path){
        $res = file_get_contents($private_key_path);
        openssl_sign($data, $sign, $res);
        //base64编码
        $sign = base64_encode($sign);
        return $sign;
    }
    protected function HttpPost($url,$data){
        $curl = curl_init(); 
        $this_header = array("content-type: application/x-www-form-urlencoded; charset=UTF-8");
        curl_setopt($curl, CURLOPT_HTTPHEADER,$this_header);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data)));
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);  
        $tmpInfo = curl_exec($curl); 
        curl_close($curl);
        return $tmpInfo;
    }
}